#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>

#include "nstar_m26_dev.h"
#include "nstar_m26_api.h"

extern void fun_m26_pwctl(void);
extern void fun_m26_send(const unsigned char *tbuf, unsigned int len);
extern unsigned int fun_m26_rec(unsigned char *rbuf);

#define M26_powerctl 	fun_m26_pwctl
#define M26_send_data	fun_m26_send
#define M26_block_rec	fun_m26_rec
#define M26_os_sleep(nms)	//串口启动了vt time ,不再需要延时

static unsigned char m26_rxbuf[M26_MAX_RLEN+1];
static unsigned char m26_tx_buf[M26_MAX_SLEN+1];

static char* check_ack(unsigned char *rbuf, char *str)
{
	char *strx= NULL;
	if(str != NULL)
		strx= strstr((char*)rbuf, str);
	return strx;
}

void M26_printf(char* fmt,...)
{  
	unsigned int len;
	unsigned char *pbuf = m26_tx_buf;
	va_list ap;
	va_start(ap,fmt);
	len=vsnprintf((char*)pbuf,M26_MAX_SLEN,fmt,ap);
	va_end(ap);
	if(len >= M26_MAX_SLEN)
		printf("at printf len overflow %02d\r\n",len);
	M26_send_data(pbuf, len);
}


unsigned char M26_cmd1(char *cmd,char *ack, unsigned short waittime)
{
	unsigned char ret=0;
	M26_printf("%s\r\n",cmd);	//发送命令	(按手册不需要\r\n，只需要单\n)
	if(ack&&waittime){			//需要等待应答
		while(--waittime)		//等待倒计时
		{ 
			if(M26_block_rec(m26_rxbuf)){
				if(check_ack(m26_rxbuf, ack)){
					ret= 1;
					break;    	//得到正确响应，退出 
				}
			} 
			M26_os_sleep(100);
		}
	}
	return ret;
}


unsigned char M26_cmd2(char *cmd, char *ack1, char *ack2, unsigned short waittime)
{
	unsigned char ret=0;
	M26_printf("%s\r\n",cmd);	
	while(--waittime)			
	{ 
		if(M26_block_rec(m26_rxbuf)) 	
		{
			if(check_ack(m26_rxbuf, ack1)){
				ret= 1;
				break;
			}
			if(check_ack(m26_rxbuf, ack2)){
				ret= 2;
				break;
			}
			M26_os_sleep(100);
		}
	}
	return ret;
}

unsigned char M26_cmd(char *cmd,char *ack)
{
	return M26_cmd1(cmd, ack, M26_COMM_ACKTCNT);
}

char *M26_get_data(char *cmd,char *ack, unsigned short waittime)
{
	char *ret=NULL;
	M26_printf("%s\r\n",cmd);	//发送命令	(按手册不需要\r\n，只需要单\n)
	if(ack&&waittime){			//需要等待应答
		while(--waittime)		//等待倒计时
		{ 
			if(M26_block_rec(m26_rxbuf)) 	
			{
				ret= check_ack(m26_rxbuf, ack);
				if(ret != NULL){
					break;    	//得到正确响应，退出 
				}
			} 
			M26_os_sleep(100);
		}
	}
	return ret;
}


void M26_dev_init(M26_DEV* p_dev)
{
	static volatile long timer[8];
	/*没有this指针，多设备需要构建多套函数*/
	memset(p_dev, 0, sizeof(M26_DEV));
	p_dev->step= 0;
	p_dev->rbuf= m26_rxbuf;
	p_dev->pwrctl= 	M26_powerctl;//开机，重启模块
	p_dev->printf= M26_printf;
	p_dev->send= M26_send_data;
	p_dev->cmd= M26_cmd;
	p_dev->cmd1= M26_cmd1;
	p_dev->cmd2= M26_cmd2;
	p_dev->get_data= M26_get_data;
	p_dev->private= timer;
}


